package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.StringUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.RoundImageView;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONObject;

import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * 预约挂号 确认页面
 * Created by gaoge on 2016/11/29.
 */

public class OrderAffirmActivity extends BaseActivity implements View.OnClickListener {

    //返回键
    private ImageView img_back = null;
    //标题
    private TextView title_name = null;
    //头像
    private RoundImageView image = null;
    //姓名
    private TextView name = null;
    //身份
    private TextView position = null;
    //科室
    private TextView office = null;
    //擅长
    private TextView data = null;
    //预约规则
    private TextView rule = null;
    //就诊时间
    private TextView time = null;
    //就诊人
    private TextView user_name = null;
    //提交按钮
    private TextView button = null;
    //预约结果布局
    private LinearLayout result_linearlayout = null;
    //预约结果
    private TextView user_result = null;
    //预约码
    private TextView user_code = null;
    //医院
    private TextView activity_doctorlist_doctorname = null;
    //医院等级
    private TextView activity_doctorlist_grade = null;
    //数据显示页面
    private LinearLayout linearlayout = null;
    //预约结果提示语
    private TextView result = null;
    //加载框
    AlertDialog alertDialog;
    //记录当前页面状态
    private boolean lean = false;
    /**
     * 放大动画
     */
    private ScaleAnimation appearAnimation = null;
    //星期数组
    private String[] str = {"星期一", "星期二", "星期三", "星期四", "星期五"};
    //记录医院ID
    private int hospitalID = 0;
    //记录医生ID
    private int ID = 0;
    //获取用户选择的日期（周一到周五）
    private int week = 0;
    //获取用户选择的时间段（上午或者下午）
    private int allDay = 1;
    //记录预约规则
    private String ruleString = "";
    //记录取号时间
    private String reservationGetTicketTime = "";
    //预约成功返回的预约码
    private String reservationCode = "";
    //数据库
    private DBManager db = null;
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_affirm);
        //初始化组件
        initialization();
        //实现
        realize();
    }

    /**
     * 初始化组件，并给相应控件添加单击事件
     * view
     */
    private void initialization() {
        db = new DBManager(this);
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.doctor_no) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.doctor_no) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();
        title_name = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        linearlayout = (LinearLayout) findViewById(R.id.linearlayout);
        image = (RoundImageView) findViewById(R.id.image);
        name = (TextView) findViewById(R.id.name);
        position = (TextView) findViewById(R.id.position);
        office = (TextView) findViewById(R.id.office);
        data = (TextView) findViewById(R.id.data);
        rule = (TextView) findViewById(R.id.rule);
        time = (TextView) findViewById(R.id.time);
        user_name = (TextView) findViewById(R.id.user_name);
        button = (TextView) findViewById(R.id.button);
        result_linearlayout = (LinearLayout) findViewById(R.id.result_linearlayout);
        result = (TextView) findViewById(R.id.result);
        user_result = (TextView) findViewById(R.id.user_result);
        user_code = (TextView) findViewById(R.id.user_code);
        activity_doctorlist_doctorname = (TextView) findViewById(R.id.activity_doctorlist_doctorname);
        activity_doctorlist_grade = (TextView) findViewById(R.id.activity_doctorlist_grade);
        img_back.setOnClickListener(this);
        button.setOnClickListener(this);
        // 控件显示动画
        appearAnimation = new ScaleAnimation(0.1f, 1f, 0.1f, 1f, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        appearAnimation.setDuration(1000);// 设置时间
        appearAnimation.setFillAfter(false);// 图片点击后，保存放大后的大小
    }

    /**
     * 功能实现
     */
    private void realize() {
        try {
            //设置标题
            title_name.setText("确认预约信息");
            //获取数据
            Bundle bundle = this.getIntent().getExtras();
            ID = bundle.getInt("id");
            //设置医生数据
            if (!bundle.getString("name").equals("") && !bundle.getString("name").equals("null")) {
                name.setText(bundle.getString("name"));
            } else {
                name.setText("");
            }
            if (!bundle.getString("professionalTitle").equals("") && !bundle.getString("professionalTitle").equals("null")) {
                position.setText(bundle.getString("professionalTitle"));
            } else {
                position.setText("");
            }
            if (!bundle.getString("primaryDepartmentName").equals("") && !bundle.getString("primaryDepartmentName").equals("null")) {
                office.setText(bundle.getString("primaryDepartmentName"));
            } else {
                office.setText("科室");
            }
            if (bundle.getString("photoUrl") != null && !bundle.getString("photoUrl").equals("") && !bundle.getString("photoUrl").equals("null")) {
                imageLoader.displayImage(bundle.getString("photoUrl"), image, options);
            } else {
                image.setImageResource(R.mipmap.doctor_no);
            }
            if (bundle.getString("specialty") != null && !bundle.getString("specialty").equals("") && !bundle.getString("specialty").equals("null")) {
                data.setText(bundle.getString("specialty"));
            } else {
                data.setText("");
            }
            if (!bundle.getString("primaryHospitalName").equals("") && !bundle.getString("primaryHospitalName").equals("null")) {
                activity_doctorlist_doctorname.setText(bundle.getString("primaryHospitalName"));
            } else {
                activity_doctorlist_doctorname.setText("等级");
            }
            if (!bundle.getString("primaryHospitalLevel").equals("") && !bundle.getString("primaryHospitalLevel").equals("null")) {
                activity_doctorlist_grade.setText(bundle.getString("primaryHospitalLevel"));
            } else {
                activity_doctorlist_grade.setText("医院");
            }
            user_name.setText(bundle.getString("userName"));
            String timeShow = "";
            timeShow = bundle.getString("time");
            week = bundle.getInt("week");
            timeShow = timeShow + "  " + str[week - 1];
            allDay = bundle.getInt("allDay");
            if (allDay == 1) {
                timeShow = timeShow + "  上午";
            } else {
                timeShow = timeShow + "  下午";
            }
            time.setText(timeShow);
            hospitalID = bundle.getInt("hospitalID");
        } catch (Exception e) {
            ToastUtil.showToast(this, "获取医生信息失败");
        }
        //获取数据
        if (NetworkUtil.isNetworkAvailable(this)) {
            alertDialog = new MyAlertDialog().ShowDialog(OrderAffirmActivity.this, R.layout.dialog_loading);
            alertDialog.setCancelable(true);
            getRule();
        }

    }

    /**
     * 单击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //返回键
            case R.id.img_back:
                finish();
                break;
            //预约规则
            case R.id.rule:
                showRule();
                break;
            //提交
            case R.id.button:
                if (lean) {
                    finish();
                } else {
                    //调用提交方法
                    setData();
                }
                break;
        }
    }

    /**
     * 提交数据
     */
    private void setData() {
        alertDialog = new MyAlertDialog().ShowDialog(OrderAffirmActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HashMap<String, Integer> param = new HashMap<>();
                    param.put("doctorId", ID);
                    param.put("date", week);
                    param.put("time", allDay);
                    String p = new Gson().toJson(param);
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url(APIMethod.OrderSubmit).post(formBody).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    JSONObject jsonObject = new JSONObject(bodys);
                    if (code == 200 || code == 204) {
                        reservationCode = jsonObject.getString("reservationCode");
                        loginHandler.sendEmptyMessage(1);
                    } else {
                        jsonObject = new JSONObject(jsonObject.getString("error"));
                        reservationGetTicketTime = jsonObject.getString("message");
                        loginHandler.sendEmptyMessage(3);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (alertDialog != null) {
                alertDialog.dismiss();
            }
            switch (msg.what) {
                case 1:
                    lean = true;
                    title_name.setText("预约结果");
                    button.setText("确定");
                    user_code.setText(reservationCode);
                    result_linearlayout.setVisibility(LinearLayout.VISIBLE);
                    result_linearlayout.startAnimation(appearAnimation);
                    rule.setVisibility(LinearLayout.GONE);
                    if (reservationGetTicketTime != null && !reservationGetTicketTime.equals("") && !reservationGetTicketTime.equals("null")) {
                        try {
                            JSONObject eventObject = new JSONObject();
                            eventObject.put("预约挂号成功", "用于统计预约挂号人数");
                            ZhugeSDK.getInstance().track(getApplicationContext(), "预约挂号成功", eventObject);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        result.setText(StringUtil.ToDBC("取号时间:" + reservationGetTicketTime));
                        result.setVisibility(TextView.VISIBLE);
                    }
                    break;
                case 2:
                    rule.setOnClickListener(OrderAffirmActivity.this);
                    break;
                case 3:
                    lean = true;
                    button.setText("确定");
                    result.setText(StringUtil.ToDBC(reservationGetTicketTime));
                    result.setVisibility(TextView.VISIBLE);
                    break;
                default:
                    break;
            }
        }
    };

    //加载框
    MyAlertDialog dialog;

    /**
     * 预约规则
     */
    private void showRule() {
        try {
            //加载弹出框
            dialog = new MyAlertDialog();
            dialog.rule_Dialog(OrderAffirmActivity.this, R.layout.rule_dialog);
            TextView data = dialog.getData();
            data.setText(StringUtil.ToDBC(ruleString));
            TextView cancel_text = dialog.getCancel_text();
            cancel_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取预约规则
     *
     * @return
     */
    public void getRule() {
//
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.OrderRule(hospitalID)).build();
                    Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 200 || code == 204) {
                        JSONObject jsonObject = new JSONObject(bodys);
                        ruleString = jsonObject.getString("reservationRule");
                        reservationGetTicketTime = jsonObject.getString("reservationGetTicketTime");
                    }
                    loginHandler.sendEmptyMessage(2);
                } catch (Exception e) {
                    loginHandler.sendEmptyMessage(2);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
